import {
  Button,
  message,
  Modal,
  Pagination,
  Space,
  Table,
  TableColumn,
  TypographyText,
  Upload
} from 'ant-design-vue'
import { error } from 'console'
import moment from 'moment'
import {
  computed,
  defineComponent,
  nextTick,
  onMounted,
  PropType,
  ref,
  toRefs
} from 'vue'
import { useRouter } from 'vue-router'
import * as xlsx from 'xlsx'

import { marketingApi } from '@/apis'
import { importOrders } from '@/apis/riverTypes'
import { type ProTableProps, type ProTableRef, ProTable } from '@/components'
import { TABLE_FORMAT, TABLE_ITEM_RENDER, TABLE_RENDERER } from '@/constants'
import { useDialog } from '@/hooks'
import { bus } from '@/utils'
import { handlePrice } from '@/utils/bsshow'

export default defineComponent({
  name: 'ExpressReplacement',
  props: {
    peoples: {
      type: Array as PropType<Array<importOrders>>,
      required: true
    }
  },
  emits: ['dataCallback'],
  setup(props, { emit }) {
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const importInfo = ref([] as any[])
    const newRowNum = ref([] as any[])
    const showSetPriceDlg = ref(false)
    const optionGoodsItemCur = ref({} as any)
    const syncLoading = ref(false)
    const peopleList = ref(props.peoples as any[])
    const showSortDialog = ref(false)
    const showModal = ref(false)
    const dialogLoading = ref(false)
    const { showConfirm } = useDialog()
    const tableRef = ref({} as ProTableRef)
    const tableConfig = ref({
      fixedHeight: true,
      options: {
        border: true,
        align: 'center',
        toolbarConfig: {
          slots: {
            buttons: 'batchButtons'
          }
        },
        formConfig: {
          items: []
        },
        columnConfig: {
          minWidth: 100,
          resizable: true
        },
        checkboxConfig: {
          showHeader: true,
          range: true
        },
        columns: [
          {
            title: '更换时间',
            field: 'createTime',
            width: 150,
            formatter: [TABLE_FORMAT.Date, 'yyyy-MM-dd HH:mm:ss']
          },
          {
            title: '更换订单数量',
            field: 'changeCount'
          },
          {
            title: '操作人',
            field: 'createUser'
          },
          {
            title: '更换详情',
            fixed: 'right',
            slots: {
              default: 'operation'
            },
            width: 100
          }
        ],
        pagerConfig: {
          pageSize: 15
        },
        proxyConfig: {
          form: true,
          props: {
            result: 'dataList',
            total: 'page.totalCount'
          },
          ajax: {
            query: async ({ page, form }) => {
              const data = await marketingApi.getExpressionList({
                pageSize: page.pageSize,
                currentPage: page.currentPage
                // ...form
              })
              return data
            }
          }
        }
      }
    } as ProTableProps)

    const modalConfig = ref({
      modalColumns: [
        {
          title: '原始单号',
          field: 'orderSn',
          width: 200
        },
        {
          title: '正确物流单号',
          field: 'logisticsNo'
        },
        {
          title: '正确物流公司',
          field: 'logisticsName'
        },
        {
          title: '仓库',
          field: 'warehouse',
          width: 120
        },
        {
          title: '反馈日期',
          field: 'feedbackDate',
          formatter: [TABLE_FORMAT.Date, 'yyyy-MM-dd ']
        },
        {
          title: '原因备注',
          field: 'causeRemarks'
        },
        {
          title: '商品名称',
          field: 'productName'
        }
      ],
      data: [] as any[]
    })

    onMounted(() => {
      bus.on('refreshJdgGoodsList', () => {
        nextTick(() => {
          tableRef.value.refresh()
        })
      })
    })

    //获取选中的项
    function getSelectedItems() {
      return tableRef.value.table?.getCheckboxRecords()
    }
    const router = useRouter()

    //导入订单excel
    const failList = ref()
    async function importOrder(params) {
      try {
        const formData = new FormData()
        formData.append('file', params.file)
        peopleList.value = await marketingApi.getImportInfo(formData)
        modalConfig.value.data = peopleList.value
        dialogLoading.value = false
        showModal.value = true
        const newFail = peopleList.value.failList
        const rowFailNum = newFail.map(item => {
          return item.rowNum
        })
        // newRowNum.value = rowFailNum.join(',')
        // if (newRowNum.value) {
        //   message.error(
        //     `第${newRowNum.value}条导入失败，导入成功${peopleList.value.successRow}条`
        //   )
        // } else if (peopleList.value?.successRow) {
        //   message.success(`导入成功，共${peopleList.value.successRow}条`)
        // }
      } catch {}
    }
    //刷新回调
    // async function refresh() {
    //   await tableRef.value.table.commitProxy('query')
    // }
    // 弹窗确定
    async function handleConfirm() {
      const data = peopleList.value
      try {
        dialogLoading.value = true
        await marketingApi.getExpressionImport(data)
        modalConfig.value.data = data // 更新数据列
        tableRef.value.refresh()
      } finally {
        showModal.value = false
        dialogLoading.value = false
      }
    }

    // 查看
    function handleView(row) {
      router.push({
        name: 'ExpressDetail',
        query: {
          id: row.id,
          createTime: row.createTime,
          changeCount: row.changeCount,
          createUser: row.createUser
        }
      })
    }
    return {
      tableRef,
      tableConfig,
      showSetPriceDlg,
      optionGoodsItemCur,
      syncLoading,
      showSortDialog,
      dialogLoading,
      peopleList,
      importInfo,
      failList,
      showModal,
      modalConfig,
      currentPage,
      pageSize,
      total,
      handleConfirm,
      handleView,
      importOrder,
      getSelectedItems
    }
  },
  render() {
    return (
      <div>
        <ProTable
          ref="tableRef"
          v-slots={{
            batchButtons: () => (
              <Space>
                <Upload
                  accept=".xlsx,.xls"
                  name="file"
                  customRequest={this.importOrder}
                  showUploadList={false}
                >
                  <Button type="primary">导入数据</Button>
                </Upload>
                <Button type="link" size="small">
                  <a href="https://yswy-agent.yjdfytmall.com/20230925/dbc4b7a7-1453-47e5-91d2-568de41e59af.xlsx ">
                    下载导入模板
                  </a>
                </Button>
              </Space>
            ),
            salePrice: ({ row }) => {
              return <Space>{handlePrice(row.salePrice, row.saleGold)}</Space>
            },
            isSettlement: ({ row }) => {
              return (
                <Space>
                  {row.isSettlement == 0 ? (
                    <TypographyText type="danger">否</TypographyText>
                  ) : (
                    <TypographyText type="success">是</TypographyText>
                  )}
                </Space>
              )
            },
            operation: ({ row }) => (
              <Space>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleView(row)}
                >
                  查看
                </Button>
              </Space>
            )
          }}
          {...this.tableConfig}
        />
        <Modal
          v-model:visible={this.showModal}
          width={'1200px'}
          onOk={this.handleConfirm}
          onUpdate:modelValue={val => (this.showModal = val)}
        >
          <span style={{ marginLeft: '500px', fontSize: '25px' }}>
            更换信息确认
          </span>
          <ProTable
            // ref="tableRef"
            // dataProp={this.currentData}
            dataProp={this.modalConfig.data}
            columns={this.modalConfig.modalColumns}
            {...this.modalConfig}
          ></ProTable>
        </Modal>
      </div>
    )
  }
})
